package com.example.bluetoothclicker.func

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.util.Log
import android.widget.Toast
import java.io.IOException
import java.util.concurrent.Executors

object BluetoothConnectionManager {

    private val bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    private var server: MultiBluetoothServer? = null
    private var bluetoothClient: BluetoothClient? = null
    private val executor = Executors.newSingleThreadExecutor()

    // 状态回调接口
    private var statusCallback: ((String) -> Unit)? = null

    fun setStatusCallback(callback: (String) -> Unit) {
        statusCallback = callback
    }

    private fun notifyStatusChange(status: String) {
        statusCallback?.invoke(status)
    }

    // 初始化服务端
    fun initializeServer(
        maxConnections: Int,
        onClientConnected: (BluetoothSocket) -> Unit,
        onStatusChanged: (String) -> Unit
    ) {
        if (server == null) {
            server = MultiBluetoothServer(bluetoothAdapter, maxConnections)
        }
        startServer(onClientConnected, onStatusChanged)
    }

    // 启动服务端
    fun startServer(onClientConnected: (BluetoothSocket) -> Unit, onStatusChanged: (String) -> Unit) {
        server?.startServer(onClientConnected, onStatusChanged)
    }

    // 停止服务端
    fun stopServer() {
        try {
            server?.stopServer()
            notifyStatusChange("服务端已停止。")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 连接其他设备作为客户端
    fun connectToServer(
        device: BluetoothDevice,
        onConnected: (String) -> Unit,
        onError: (String) -> Unit
    ) {
        executor.execute {
            try {
                stopServer() // 停止服务端，避免冲突
                bluetoothClient = BluetoothClient(device)
                bluetoothClient?.connectToServer(
                    onConnected = { socket ->
                        notifyStatusChange("已连接到 ${socket.remoteDevice.name}")
                        onConnected("已连接到 ${socket.remoteDevice.name}")
                    },
                    onError = { error ->
                        notifyStatusChange("连接失败: ${error.message}")
                        onError("连接失败: ${error.message}")
                        restartServer()
                    }
                )
            } catch (e: Exception) {
                notifyStatusChange("连接失败: ${e.message}")
                onError("连接失败: ${e.message}")
                restartServer()
            }
        }
    }

    // 断开客户端连接并重启服务端
    fun disconnectFromServer() {
        try {
            bluetoothClient?.releaseResources()
            notifyStatusChange("客户端已断开连接。")
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            bluetoothClient = null
            restartServer()
        }
    }

    // 重启服务端
    private fun restartServer() {
        server?.let {
            try {
                startServer(
                    onClientConnected = { socket ->
                        notifyStatusChange("客户端已连接: ${socket.remoteDevice.name}")
                    },
                    onStatusChanged = { status ->
                        notifyStatusChange(status)
                    }
                )
                notifyStatusChange("服务端已重启。")
            } catch (e: Exception) {
                notifyStatusChange("服务端重启失败: ${e.message}")
                e.printStackTrace()
            }
        }
    }

    // 检查自身当前是否有作为客户端进行连接
    fun isConnectedAsClient(): Boolean {
        return bluetoothClient?.isConnectionActive() == true
    }

    // 检查自身当前是否有作为服务端进行连接
    fun isConnectedAsServe(): Boolean {
        return (server?.getConnectedCount() ?: 0) > 0
    }

    // 关闭所有的连接包括服务端和客户端
    fun closeAllCollected() {
        try {
            stopServer()
            disconnectFromServer()
            notifyStatusChange("所有连接已关闭。")
        } catch (e: Exception) {
            notifyStatusChange("关闭所有连接失败: ${e.message}")
            e.printStackTrace()
        }
    }

    // 获取当前的客户端实例
    fun getClient(): BluetoothClient? {
        if (bluetoothClient==null)Log.d("BluetoothClient", "客户端无效")

        return bluetoothClient
    }

    fun getClientFromServe(macAddress: String): BluetoothSocket? {
        return server?.getClient(macAddress)
    }

    fun closeClientOnServe(macAddress: String): Unit? {
        return server?.closeClient(macAddress)
    }

    /**
     * 服务端接收消息
     * @param onMessageReceived 回调，用于处理客户端发送的消息
     * @param onStatusChanged 回调，用于更新服务端的状态
     */
    fun startServerMessageListening(
        onMessageReceived: (String, String) -> Unit,
        onStatusChanged: (String) -> Unit
    ) {
        // 启动消息监听逻辑
        server?.startMessageListening(
            onMessageReceived = { macAddress, message ->
                onMessageReceived(macAddress, message) // 回调传出 MAC 地址和消息内容
            },
            onStatusChanged = { status ->
                onStatusChanged(status)
            }
        )
    }

    fun closeServerMessageListening(
        onStatusChanged: (String) -> Unit
    ) {
        // 停止消息监听逻辑
        server?.closeMessageListening(
            onStatusChanged = { status ->
                onStatusChanged(status)
            }
        )
    }

    // 服务端广播消息
    fun broadcastMessage(message: String) {
        try {
            server?.broadcastMessage(message)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    // 释放所有资源（服务端和客户端）
    fun releaseResources() {
        try {
            stopServer()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            server = null
        }

        try {
            bluetoothClient?.releaseResources()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            bluetoothClient = null
        }

        notifyStatusChange("所有资源已释放。")
    }
}
